import React, { useEffect, useState } from 'react';

import { AutoComplete, Button, Card, Form, Input, Popconfirm, Select, Tooltip } from 'antd';
import debounce from 'lodash/debounce';

import { BottomAction } from '@/components';
import Icon from '@/components/IconPro';
import LabelValue from '@/components/LabelValue';
import OrganizationSelect from '@/components/OrganizationSelect';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { defaultFormatResult, useRequest } from '@/hooks';
import { DynamicTable } from '@/pages/TurnoverSetting/EntrySetting/components';
import { formatResultByFetchDetail, onSuccessBySave } from '@/pages/TurnoverSetting/EntrySetting/util';
import pageTabUtil from '@/utils/pageTabUtil';
import { genID } from '@/utils/utils';

import { getEntryAssetsConfig, getEntryAssetsConfigDetail, postEntryAssetsConfig } from '../services';
import styles from './index.less';

const { Option } = Select;
const EntryAssetAllocationEdit = ({ form, location }) => {
    const [customSoftData, setCustomSoftData] = useState([]);
    const [professionalSoftData, setProfessionalSoftData] = useState([]);
    const [virtualSystemData, setVirtualSystemData] = useState([]);
    const [detailVirtualSystemData, setDetailVirtualSystemData] = useState([]);
    const { getFieldDecorator, validateFieldsAndScroll } = form;
    const { id } = location.query;
    // 获取通用软件和专业软件数据源
    const { data: initData } = useRequest(() => getEntryAssetsConfig(), {
        ...defaultFormatResult
    });

    // 获取通用软件和专业软件数据源
    const { run: submitEntryAssetsConfig, loading } = useRequest(values => postEntryAssetsConfig(values), {
        manual: true,
        onSuccess: onSuccessBySave
    });

    // 获取详情
    const { data: detailData, run: fetchEntryAssetsConfigDetail, loading: detailDataLoading } = useRequest(
        value => getEntryAssetsConfigDetail(value),
        {
            manual: true,
            formatResult: formatResultByFetchDetail
        }
    );
    // 软件数据组装
    const filterSoftData = (arr, detailArr) => {
        const selectedArr = detailArr?.map(item => item.softname);
        const tempArr = arr?.map(item => {
            const disabled = selectedArr?.includes(item?.softname);
            return {
                text: item.softname,
                disabled,
                selectRow: undefined,
                key: genID(10)
            };
        });
        if (selectedArr?.length > 0) {
            selectedArr.forEach((item, index) => {
                if (tempArr?.length > 0) {
                    tempArr.forEach((subItem, subIndex) => {
                        if (item === subItem.text) {
                            tempArr[subIndex].selectRow = index;
                        }
                    });
                }
            });
        }
        return tempArr;
    };
    // 虚拟资产数据组装
    const filterVirtualSystemData = (arr, detailArr) => {
        const selectedArr = detailArr?.map(item => item.assetName);
        const tempArr = arr?.map(item => {
            const disabled = selectedArr?.includes(item?.assetName);
            return {
                text: item.assetName,
                disabled: disabled || false,
                assetCode: item.assetCode,
                assetUrl: item.assetUrl,
                isDefault: item.isDefault,
                selectRow: undefined,
                key: genID(10)
            };
        });
        if (selectedArr?.length > 0) {
            selectedArr.forEach((item, index) => {
                if (tempArr?.length > 0) {
                    tempArr.forEach((subItem, subIndex) => {
                        if (item === subItem.text) {
                            tempArr[subIndex].selectRow = index;
                        }
                    });
                }
            });
        }
        return tempArr;
    };
    // 专业软件选择项\通用软件、虚拟资产选择项;
    const onSelect = (value, recordKey, selected, source, sourceName) => {
        const tempArr = source?.map(item => {
            const tempObj = { ...item };
            if (tempObj?.selectRow === recordKey) {
                tempObj.disabled = false;
                if (selected) {
                    tempObj.selectRow = undefined;
                }
            }
            if (tempObj.text === value && tempObj?.selectRow !== recordKey) {
                tempObj.disabled = true;
                tempObj.selectRow = recordKey;
            }
            return tempObj;
        });
        if (sourceName === 'virtualSystemData') {
            setVirtualSystemData(tempArr);
        }
        if (sourceName === 'professionalSoftData') {
            setProfessionalSoftData(tempArr);
        }
        if (sourceName === 'customSoftData') {
            setCustomSoftData(tempArr);
        }
    };
    // 通用软件校验
    const handleValidate = debounce((values, type, force = false) => {
        const needValidateFields = [];
        values.forEach((item, index) => {
            const currentKey =
                type === 'commonSoftware'
                    ? `commonSoftware[${index}].softname`
                    : `professionalSoftware[${index}].softname`;
            // 为了解决循环校验问题, 设置一个时钟, 来延迟校验
            if (form.getFieldError(currentKey)) {
                needValidateFields.push(currentKey);
            }
        });
        // 设置 force: true, 强制校验, 要不然value值没有变, 就会取历史的校验结果
        form.validateFields(needValidateFields, { force });
    }, 100);
    // 通用软件
    const commonSoftwareColumns = [
        {
            title: '名称',
            dataIndex: 'softname',
            key: 'softname',
            render: ({ text, fieldDecorator, recordKey }) => (
                <>
                    {fieldDecorator('softname', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '通用软件名称不能为空'
                            },
                            {
                                validator(rule, val, callback) {
                                    const selectedValues = form.getFieldValue('commonSoftware');
                                    // 数据过滤
                                    const selectedArr = selectedValues?.map(item => item.softname);
                                    selectedArr.splice(recordKey, 1);
                                    if (val?.length > 50) {
                                        callback('名称只允许输入50个字符！');
                                        return;
                                    }
                                    if (selectedArr.filter(Boolean).includes(val)) {
                                        callback('名称重复!');
                                    } else {
                                        callback();
                                        handleValidate(selectedValues, 'commonSoftware');
                                    }
                                }
                            }
                        ],
                        validateTrigger: ['onBlur']
                    })(
                        <AutoComplete
                            style={{ width: 200 }}
                            filterOption={() => true}
                            placeholder="请选择或输入"
                            onSelect={value => onSelect(value, recordKey, true, customSoftData, 'customSoftData')}
                            onChange={value => onSelect(value, recordKey, true, customSoftData, 'customSoftData')}
                            getPopupContainer={() => document.getElementById('ctr')}
                        >
                            {customSoftData?.map(item => {
                                const { key, text: label, disabled } = item;
                                return (
                                    <AutoComplete.Option
                                        key={key}
                                        value={label}
                                        optionLabelProp={disabled}
                                        disabled={disabled}
                                    >
                                        {label}
                                    </AutoComplete.Option>
                                );
                            })}
                        </AutoComplete>
                    )}
                </>
            )
        },
        {
            title: '类型',
            dataIndex: 'softType',
            key: 'softType',
            render: ({ text, fieldDecorator }) => (
                <>
                    {fieldDecorator('softType', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '通用软件类型不能为空'
                            }
                        ]
                    })(
                        <Select placeholder="请选择" style={{ width: '200px' }}>
                            {initData?.commonSoftware.map(item => (
                                <Option key={item.id} value={item.softType}>
                                    {item.softType}
                                </Option>
                            ))}
                        </Select>
                    )}
                </>
            )
        },
        {
            title: '操作',
            dataIndex: 'operator',
            width: '120px',
            align: 'center',
            render: ({ index, methods, getFieldValue, recordKey }) => (
                <>
                    <Popconfirm
                        title="你确定删除吗?"
                        onConfirm={() => {
                            const softname = getFieldValue('softname');
                            const selectedValues = form.getFieldValue('commonSoftware');

                            onSelect(softname, recordKey, false, customSoftData, 'customSoftData');

                            methods.remove(index);
                            handleValidate(selectedValues, 'commonSoftware', true);
                        }}
                    >
                        <Tooltip placement="top" title="删除">
                            <Icon.Button
                                dark
                                icon="iconlistfunction_delete_icon_default"
                                className={styles.fontSize22}
                            />
                        </Tooltip>
                    </Popconfirm>
                </>
            )
        }
    ];
    // 专业软件
    const professionalSoftwareColumns = [
        {
            title: '名称',
            dataIndex: 'softname',
            key: 'softname',
            render: ({ text, fieldDecorator, recordKey }) => (
                <>
                    {fieldDecorator('softname', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '专业软件名称不能为空'
                            },
                            {
                                validator(rule, val, callback) {
                                    const selectedValues = form.getFieldValue('professionalSoftware');
                                    // 数据过滤
                                    const selectedArr = selectedValues?.map(item => item.softname);
                                    selectedArr.splice(recordKey, 1);
                                    if (val?.length > 50) {
                                        callback('名称只允许输入50个字符！');
                                        return;
                                    }
                                    if (selectedArr.filter(Boolean).includes(val)) {
                                        callback('名称重复!');
                                    } else {
                                        callback();
                                        handleValidate(selectedValues, 'professionalSoftware');
                                    }
                                }
                            }
                        ],
                        validateTrigger: ['onBlur']
                    })(
                        <AutoComplete
                            style={{ width: 200 }}
                            filterOption={() => true}
                            placeholder="请选择或输入"
                            onSelect={value =>
                                onSelect(value, recordKey, true, professionalSoftData, 'professionalSoftData')
                            }
                            getPopupContainer={() => document.getElementById('ctr')}
                            onChange={value =>
                                onSelect(value, recordKey, true, professionalSoftData, 'professionalSoftData')
                            }
                        >
                            {professionalSoftData?.map(item => {
                                const { key, text: label, disabled } = item;
                                return (
                                    <AutoComplete.Option
                                        key={key}
                                        value={label}
                                        optionLabelProp={disabled}
                                        disabled={disabled}
                                    >
                                        {label}
                                    </AutoComplete.Option>
                                );
                            })}
                        </AutoComplete>
                    )}
                </>
            )
        },
        {
            title: '操作',
            dataIndex: 'operator',
            width: '120px',
            align: 'center',
            render: ({ index, methods, recordKey, getFieldValue }) => (
                <>
                    <Popconfirm
                        title="你确定删除吗?"
                        onConfirm={() => {
                            const softname = getFieldValue('softname');

                            const selectedValues = form.getFieldValue('professionalSoftware');
                            onSelect(softname, recordKey, false, professionalSoftData, 'professionalSoftData');

                            methods.remove(index);
                            handleValidate(selectedValues, 'professionalSoftware', true);
                        }}
                    >
                        <Tooltip placement="top" title="删除">
                            <Icon.Button
                                dark
                                icon="iconlistfunction_delete_icon_default"
                                className={styles.fontSize22}
                            />
                        </Tooltip>
                    </Popconfirm>
                </>
            )
        }
    ];
    // 虚拟资产
    const accountColumns = [
        {
            title: '名称',
            dataIndex: 'assetCode',
            key: 'assetCode',
            render: ({ text, fieldDecorator, setFieldsValue, recordKey, record }) => (
                <>
                    {fieldDecorator('assetCode', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '虚拟资产名称不能为空'
                            }
                        ]
                    })(
                        <Select
                            placeholder="请选择"
                            style={{ width: 200 }}
                            getPopupContainer={() => document.getElementById('ctr')}
                            onSelect={value => {
                                // 获取当前选择的数据，进行赋值
                                const selectData = virtualSystemData.filter(item => item.assetCode === value);
                                const { text: assetName, assetUrl, isDefault } = selectData[0];
                                setFieldsValue({
                                    assetUrl,
                                    assetName,
                                    isDefault
                                });
                                onSelect(assetName, recordKey, true, virtualSystemData, 'virtualSystemData');
                            }}
                            disabled={record.isDefault === 1}
                        >
                            {virtualSystemData?.map(item => {
                                const { key, text: label, assetCode } = item;
                                return (
                                    <Option key={key} value={assetCode} disabled={item.disabled}>
                                        {label}
                                    </Option>
                                );
                            })}
                        </Select>
                    )}
                </>
            )
        },
        {
            title: '网址',
            dataIndex: 'assetUrl',
            key: 'assetUrl',
            render: ({ text, fieldDecorator, record }) => (
                <>
                    {fieldDecorator('assetUrl', {
                        initialValue: text,
                        rules: [
                            {
                                required: true,
                                message: '虚拟资产网址不能为空'
                            },
                            {
                                validator(rule, val, callback) {
                                    const regex = /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/i;
                                    if (!regex.test(val)) {
                                        callback('请输入有效网址');
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(<Input placeholder="请输入" maxLength={200} disabled={record.isDefault === 1} />)}
                </>
            )
        },
        {
            dataIndex: 'assetName',
            hide: true
        },
        {
            dataIndex: 'isDefault',
            hide: true
        },
        {
            title: '操作',
            dataIndex: 'operator',
            width: '120px',
            align: 'center',
            render: ({ index, methods, getFieldValue, recordKey, record }) => (
                <>
                    <Popconfirm
                        title="你确定删除吗?"
                        disabled={record.isDefault === 1}
                        onConfirm={() => {
                            const assetName = getFieldValue('assetName');
                            onSelect(assetName, recordKey, false, virtualSystemData, 'virtualSystemData');
                            methods.remove(index);
                        }}
                    >
                        <Tooltip placement="top" title="删除">
                            <Icon.Button
                                dark
                                icon="iconlistfunction_delete_icon_default"
                                className={styles.fontSize22}
                                disabled={record.isDefault === 1}
                            />
                        </Tooltip>
                    </Popconfirm>
                </>
            )
        }
    ];
    // 提交
    const handleSubmit = () => {
        validateFieldsAndScroll((err, values) => {
            if (!err) {
                let param;
                const { commonSoftware, professionalSoftware, virtualSystem } = values;
                param = {
                    ...values,
                    commonSoftware: commonSoftware?.filter(Boolean),
                    professionalSoftware: professionalSoftware?.filter(Boolean),
                    virtualSystem: virtualSystem?.filter(Boolean)
                };
                if (id) {
                    param = {
                        ...param,
                        id,
                        isDefault: detailData?.isDefault
                    };
                } else {
                    param = {
                        ...param,
                        isDefault: 0
                    };
                }
                submitEntryAssetsConfig(param);
            }
        });
    };

    useEffect(() => {
        // 数据格式化
        const formatData = filterSoftData(initData?.commonSoftware, detailData?.commonSoftware);
        const formatVirtualSystemData = filterVirtualSystemData(initData?.virtualSystem, detailData?.virtualSystem);
        setCustomSoftData(formatData);
        // 专业软件
        setProfessionalSoftData(filterSoftData(initData?.professionalSoftware, detailData?.professionalSoftware));
        setVirtualSystemData(formatVirtualSystemData);
        // 产品需求默认选中企业邮箱
        if (!id) {
            setDetailVirtualSystemData(initData?.virtualSystem.filter(item => item.isDefault === 1));
        } else {
            setDetailVirtualSystemData(detailData?.virtualSystem);
        }
    }, [initData, detailData, id]);

    useEffect(() => {
        if (id) {
            // 获取详情
            fetchEntryAssetsConfigDetail(id);
        }
    }, [fetchEntryAssetsConfigDetail, id]);

    return (
        <PageHeaderWrapper>
            <Card
                title={`${id ? '编辑' : '添加'}模板`}
                bordered={false}
                className={styles.entryCard}
                id="ctr"
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                        <Button type="primary" onClick={() => handleSubmit()} loading={loading}>
                            提交
                        </Button>
                    </BottomAction>
                }
                loading={detailDataLoading}
            >
                <div className={styles.entryMaterialEditWrapper}>
                    <LabelValue
                        label="配置名称"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        value={() => (
                            <Form.Item>
                                {getFieldDecorator('settingName', {
                                    initialValue: detailData?.settingName,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入'
                                        }
                                    ]
                                })(<Input style={{ width: 530 }} placeholder="请输入资产配置" maxLength={200} />)}
                            </Form.Item>
                        )}
                    />
                    <LabelValue
                        label="适用行政机构"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        value={() => (
                            <Form.Item>
                                {detailData?.isDefault === 1 && '全集团'}
                                {detailData?.isDefault === 1 &&
                                    form.getFieldDecorator('administrativeScopes', {
                                        initialValue: detailData?.administrativeScopes || undefined
                                    })(<input type="hidden" />)}
                                {detailData?.isDefault !== 1 &&
                                    getFieldDecorator('administrativeScopes', {
                                        initialValue: detailData?.administrativeScopes,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择行政机构'
                                            }
                                        ]
                                    })(
                                        <OrganizationSelect
                                            isStrictly
                                            maxTagCount={2}
                                            isNeedPermission={false}
                                            onlyCompany
                                            treeCheckable
                                            style={{
                                                width: 530
                                            }}
                                        />
                                    )}
                            </Form.Item>
                        )}
                    />
                    <LabelValue
                        label="通用软件列表"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        align="top"
                        value={() => (
                            <DynamicTable
                                className={styles.tableCtr}
                                form={form}
                                initialValue={detailData?.commonSoftware || []}
                                fieldName="commonSoftware"
                                rules={[
                                    {
                                        required: true,
                                        type: 'array',
                                        message: '请填写通用软件列表'
                                    }
                                ]}
                                columns={commonSoftwareColumns}
                                style={{ width: 720 }}
                            />
                        )}
                    />
                    <LabelValue
                        label="专业软件列表"
                        align="top"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        value={() => (
                            <DynamicTable
                                form={form}
                                className={styles.tableCtr}
                                initialValue={detailData?.professionalSoftware || []}
                                fieldName="professionalSoftware"
                                rules={[
                                    {
                                        required: true,
                                        type: 'array',
                                        message: '请填写专业软件列表'
                                    }
                                ]}
                                columns={professionalSoftwareColumns}
                                style={{ width: 720 }}
                            />
                        )}
                    />
                    <LabelValue
                        label="系统帐号列表"
                        labelClassName={styles.labelWidth110}
                        requiredMark
                        align="top"
                        value={() => (
                            <DynamicTable
                                className={styles.tableCtr}
                                form={form}
                                initialValue={detailVirtualSystemData || []}
                                fieldName="virtualSystem"
                                rules={[
                                    {
                                        required: true,
                                        type: 'array',
                                        message: '请填写系统帐号列表'
                                    }
                                ]}
                                columns={accountColumns}
                                style={{ width: 720 }}
                            />
                        )}
                    />
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create()(EntryAssetAllocationEdit);
